<template>
  <view class="login-container">
    <view class="logo">
      <image src="/static/logo.png" mode="aspectFit"></image>
    </view>
    <view class="title">欢迎登录</view>
    <button class="login-btn" type="primary" @click="handleLogin">微信一键登录</button>
    <button class="userinfo-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">获取头像</button>
    <input type="nickname" class="nickname-input" placeholder="请输入昵称" @change="onInputNickname" />
  </view>
</template>

<script>
import { wxLogin } from '@/api/user'

export default {
  data() {
    return {
      loading: false,
      avatarUrl: '',
      nickname: ''
    }
  },
  methods: {
    async handleLogin() {
      if (this.loading) return
      this.loading = true
      
      try {
        // 1. 获取微信登录凭证
        const { code } = await uni.login()
        
        // 2. 调用后端登录接口
        const res = await wxLogin({
          code,
          avatarUrl: this.avatarUrl,
          nickname: this.nickname
        })
        
        // 3. 保存登录信息
        uni.setStorageSync('token', res.token)
        uni.setStorageSync('userInfo', res.user)
        
        // 4. 跳转到首页
        uni.reLaunch({
          url: '/pages/index/index'
        })
      } catch (error) {
        uni.showToast({
          icon: 'none',
          title: error.message || '登录失败'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 获取头像
    onChooseAvatar(e) {
      const { avatarUrl } = e.detail
      this.avatarUrl = avatarUrl
    },
    
    // 获取昵称
    onInputNickname(e) {
      this.nickname = e.detail.value
    }
  }
}
</script>

<style lang="scss">
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 40rpx;
  
  .logo {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 60rpx;
    
    image {
      width: 100%;
      height: 100%;
    }
  }
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 80rpx;
  }
  
  .login-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 44rpx;
    font-size: 32rpx;
    margin-bottom: 30rpx;
  }
  
  .userinfo-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 44rpx;
    font-size: 32rpx;
    margin-bottom: 30rpx;
    background-color: #07c160;
    color: #fff;
  }
  
  .nickname-input {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 44rpx;
    font-size: 32rpx;
    padding: 0 30rpx;
    background-color: #f5f5f5;
    margin-bottom: 30rpx;
  }
}
</style> 